(function(){
	//公共dialog
	$("#dialog-message-common").dialog({
		autoOpen : false,
		modal : true,
		width : $(window).width() * 0.3,
		height: $(window).height() * 0.3,
		minWidth : 200,
		minHeight: 100,
		title : "Warm Tips",
		appendTo : '#content'
	});
	//初始化3个BOX
	//idea列表
	$("#dialog-message-dialog_ideas").dialog({
		autoOpen : false,
		modal : true,
		width : $(window).width() * 0.7,
		height: $(window).height() * 0.7,
		//width : 800,
		//height: 300,
		title : "Dialog",
		appendTo : '#content'

	});
	//app增改
	$("#dialog-edit-box-apps-lists").dialog({
		autoOpen : false,
		modal : true,
		//width : $(window).width() * 0.8,
		//height: $(window).height() * 0.8,
		width : 800,
		height: 787,
		title : "Edit-Box",
		appendTo : '#content'

	});
	//idea增改
	$("#dialog-edit-box-ideas").dialog({
		autoOpen : false,
		modal : true,
		//width : $(window).width() * 0.8,
		//height: $(window).height() * 0.8,
		width : 800,
		height: 787,
		title : "Edit-Box",
		open : function(){
			//加入本次需要上传图片的图前缀
			$('#prefix1').val(Math.random());
			$('#prefix2').val(Math.random());
			$('#app_title').html($('#ideas_title').val());
			if($('#ideas_pic_url').val()[0]=='/')
			{
				$('#app_icon').attr('src',cdn_img_url + $('#ideas_pic_url').val().replace('.','_S.'));
			}else{
				$('#app_icon').attr('src',$('#ideas_pic_url').val());
			}
			$('#app_pkg_size').html($('#ideas_pkg_size').val());
			$('#app_button').html($('#ideas_button_txt').val());
			$('#app_desc').html($('#ideas_desc').html());
			$('#ad_preview').show();
			if($('#ideas_app_showtype').html() == '')
			{
				//读取app_show_type
				$.get('?m=admin&c=apps&a=lists&_c=appsData&_a=getAppShowType',function(data){
					if(data.content.results)
					{
						var html = '';
						$(data.content.results).each(function(a,b){
							html += "<option value='"+ b.key +"'>"+ b.name +"</option>";
						});
					}
					$('#ideas_app_showtype').html(html).select2();
					//console.log(data);
				});
			}
			if($('#ideas_material').html() == '')
			{
				//读取app_show_type
				$.get('?m=admin&c=apps&a=lists&_c=appsData&_a=getMaterial',function(data){
					if(data.content.results)
					{
						var html = '';
						$(data.content.results).each(function(a,b){
							html += "<option value='"+ b.key +"'>"+ b.name +"</option>";
						});
					}
					$('#ideas_material').html(html).select2();
					//console.log(data);
				});
			}
			$('#ideas_app_actiontype').val(0);
		},
		beforeClose : function(){
			//清空样式内容
			$('#title_bold').val('');
			$('#title_color').val('');
			$('#desc_bold').val('');
			$('#desc_color').val('');
			$('#pkg_size_bold').val('');
			$('#pkg_size_color').val('');
			//
			$('#app_title').html('');
			$('#app_icon').attr('src','');
			$('#app_pkg_size').html('');
			$('#app_button').html('');
			$('#app_desc').html('');
			$('#ad_preview').hide();
		},
		appendTo : '#content'
	});
	/* Add the events etc before DataTables hides a column */
	$("#datatable thead input").keyup(function() {
		datatable.fnFilter(this.value, datatable.oApi._fnVisibleToColumnIndex(datatable.fnSettings(), $("thead input").index(this)));
	});

	$("#datatable thead input").each(function(i) {
		this.initVal = this.value;
	});
	$("#datatable thead input").focus(function() {
		if (this.className == "search_init") {
			this.className = "";
			this.value = "";
		}
	});
	$("#datatable thead input").blur(function(i) {
		if (this.value == "") {
			this.className = "search_init";
			this.value = this.initVal;
		}
	});
	datatable = $('#datatable').dataTable(
	{
		"sDom" : "<'dt-top-row'lf>r<'dt-wrapper't><'dt-row dt-bottom-row'<'row'<'col-sm-6'i><'col-sm-6 text-right'p>>",
		//"sDom" : "<'dt-top-row'>r<'dt-wrapper't><'dt-row dt-bottom-row'<'row'<'col-sm-6'i><'col-sm-6 text-right'p>>",
		"bSortCellsTop" : true,
		"oTableTools" : 
		{
			"aButtons" : [
				"copy", 
				{
					"sExtends" : "collection",
					"sButtonText" : 'Save <span class="caret" />',
					"aButtons" : ["csv", "xls", "pdf"]
				}
			],
			"sSwfPath" : "js/plugin/datatables/media/swf/copy_csv_xls_pdf.swf"
		},
		"fnInitComplete" : function(oSettings, json)
		{
			$(this)
			.closest('#dt_table_tools_wrapper')
			.find('.DTTT.btn-group')
			.addClass('table_tools_group')
			.children('a.btn')
			.each(function()
				{
					$(this).addClass('btn-sm btn-default');
				}
			);
			this.fnAdjustColumnSizing(true);
		},
	    "fnDrawCallback": function ( oSettings )
	    {
	    	//pageSetUp();
	    	runEditable();
	    },
		"bFilter":true,
		"sEmptyTable": "Empty Data",
		"bServerSide": true,
		'bPaginate': true, //
		"bProcessing": true, //
		"oLanguage": langage,
		"sAjaxSource": sAjaxSource,
		"sAjaxDataProp": "content.data",
		"iDisplayLength": 25,
		"sPaginationType": "bootstrap_full",
		"sScrollX": "100%",
		"bScrollCollapse": true,
		"sScrollX": "100%",
		"sScrollXInner": "100%",
		"bScrollCollapse": false,
		"aaSorting":[[9,'desc']],
		"aoColumns": [
		     			{ "mDataProp": "order" ,"bSortable": true},
		     			{ "mDataProp": "appid" ,"bSortable": true},
		    			
		    			{ "mDataProp": "posid" ,"bSortable": true},
		     			{ "mDataProp": "pkgname" ,"bSortable": true},
		    			{ "mDataProp": "category" ,"bSortable": true},
		    			
		    			{ "mDataProp": "countries" ,"bSortable": true},
		     			{ "mDataProp": "lan" ,"bSortable": true},
		    			{ "mDataProp": "state" ,"bSortable": true},
		    			
		    			{ "mDataProp": "admin" ,"bSortable": true},
		    			{ "mDataProp": "lastModify" ,"bSortable": true},
		    			{ "mDataProp": "options" ,"bSortable": false}
		    		]
	});
	$('#submit').click(function(){
	    /*重新初始化table*/
	    var oSettings = datatable.fnSettings();
	    oSettings.sAjaxSource = sAjaxSource;
	    datatable.fnDraw();
	});
	function getParam()
	{
		var _date    = $('#date').val()    ? '&date='    + $('#date').val()    : '';
		var _country = $('#country').val() ? '&country=' + $('#country').val() : '';
		var _pkgname = $('#pkgname').val() ? '&pkgname=' + $('#pkgname').val() : '';
		var _posid   = $('#posid').val()   ? '&posid='   + $('#posid').val()   : '';
		var _planid  = $('#plan_id').val()  ? '&plan_id='  + $('#plan_id').val()  : '';
	
		return _date + _country + _pkgname + _posid + _planid;
	}
	 var _options = {
        //beforeSubmit:  showRequest,  // pre-submit callback 
        success:	   function(responseText, statusText)  {
        	if(responseText.content.data == 1)
        	{
	            $('#dialog-edit-box-apps-lists').dialog('close');
	            //console.log("submitted!");
	            $.smallBox({
	              title: "Congratulations! Your operation was submitted",
	              content: "<i class='fa fa-clock-o'></i> <i>1 seconds ago...</i>",
	              color: "#5F895F",
	              iconSmall: "fa fa-check bounce animated",
	              timeout: 4000
	            });
        	}else{
           		warningBox( responseText.content.msg,'Error',10000 );
           	}
    	    datatable.fnDraw();
        },
        error:	       function(error){
        	notice(error);
        	return false;
   	    }
    }; 
 
    // bind to the form's submit event 
	$('#fuelux-wizard').submit(function() {
		$(this).ajaxSubmit(_options);
		return false;
	});
	//ideas
	 var _options_ideas = {
       //beforeSubmit:  showRequest,  // pre-submit callback 
       success:	   function(responseText, statusText)  {
       	if(responseText.content.data == 1)
       	{
	            $('#dialog-edit-box-ideas').dialog('close');
	    		$('#dialog-message-dialog_ideas').dialog('close');
	            //console.log("submitted!");
	            $.smallBox({
	              title: "Congratulations! Your operation was submitted",
	              content: "<i class='fa fa-clock-o'></i> <i>1 seconds ago...</i>",
	              color: "#5F895F",
	              iconSmall: "fa fa-check bounce animated",
	              timeout: 4000
	            });
       	}else{
       		warningBox( responseText.content.msg,'Error',10000 );
       	}
   	    datatable.fnDraw();
       },
       error:	       function(error){
    	   notice(error);
       	return false;
  	    }
   }; 

   // bind to the form's submit event 
	$('#fuelux-wizard-ideas').submit(function() {

		$(this).ajaxSubmit(_options_ideas);
		return false;
	});
})(null);

//operation functions===============================================
/**
 * 添加App
 */
function addApp()
{
	var apps_edit_box = $('#fuelux-wizard');

	apps_edit_box.attr('action','?m=admin&c=apps&a=add');
	apps_edit_box.find('.id').val('');
	
	$('#_step1').click();
	$.get('?m=admin&c=apps&a=lists&_c=appsData&_a=getAppExcemple',function(data){
		//console.log(data);
		if(data.status != 200)
		{
			notice('Can not match any record by this id: '+ id);
			return false;
		}
		//fill fields
		data = data.content.data;
		for(var item in data)
		{
			try{
				var _type = document.getElementById(item).type;
				switch(_type)
				{
					case 'textarea':
						$('#'+item).html('');
						break;
					case 'text':
						$('#'+item).val('');
						break;
					default:
						$('#'+item).val('');
						break;
				}
			}catch(e){}
		}
		var _place = $(':radio[name="k[place]"]');
		_place.each(function(a,b){
			if($(this).val() == 0)
			{
				$(this).prop('checked',true);
			}
		});
		//脸谱radio
		var _sex = $(':radio[name="k[sex]"]');
		_sex.each(function(a,b){
			if($(this).val() == 0)
			{
				$(this).prop('checked',true);
			}
		});
		var _app_installed_num_limit = $(':radio[name="k[app_installed_num_limit]"]');
		_app_installed_num_limit.each(function(a,b){
			if($(this).val() == 0)
			{
				$(this).prop('checked',true);
			}
		});
		$('#dialog-edit-box-apps-lists').dialog({title:'Add A New App'});
		$('#dialog-edit-box-apps-lists').dialog('open');
		
		targetedCategoryIDsSellect2();
		subjectidSelect2();
		posidSelect2();
		facebook_tagsSelect2();
		
	});
}
/**
 * 编辑App
 */
function editApp(id, pkgname)
{
	var apps_edit_box = $('#fuelux-wizard');

	apps_edit_box.attr('action','?m=admin&c=apps&a=edit');
	apps_edit_box.find('.id').val('');
	$('#id').val(id);
	$('#_step1').click();
	$.get('?m=admin&c=apps&a=lists&_c=appsData&_a=getAppInfoByid', {id:id},function(data){
		//console.log(data);
		if(data.status != 200)
		{
			notice('Can not match any record by this id: '+ id);
			return false;
		}
		//fill fields
		data = data.content.data;
		for(var item in data)
		{
			try{
				var _type = document.getElementById(item).type;
				switch(_type)
				{
					case 'textarea':
						$('#'+item).html(data[item]);
						break;
					case 'text':
						$('#'+item).val(data[item]);
						break;
					default:
						$('#'+item).val(data[item]);
					break;
						break;
				}
			}catch(e){}
		}
		var _place = $(':radio[name="k[place]"]');
		_place.each(function(a,b){
			if($(this).val() == data['place'])
			{
				$(this).prop('checked',true);
			}
		});
		//脸谱radio
		var _sex = $(':radio[name="k[sex]"]');
		_sex.each(function(a,b){
			if($(this).val() == data['sex'])
			{
				$(this).prop('checked',true);
			}
		});
		var _app_installed_num_limit = $(':radio[name="k[app_installed_num_limit]"]');
		_app_installed_num_limit.each(function(a,b){
			if($(this).val() ==  data['app_installed_num_limit'])
			{
				$(this).prop('checked',true);
			}
		});
		$('#dialog-edit-box-apps-lists').dialog({title:'Edit App:  ' + pkgname});
		$('#dialog-edit-box-apps-lists').dialog('open');
		
		targetedCategoryIDsSellect2();
		subjectidSelect2();
		posidSelect2();
		facebook_tagsSelect2();
	});
}
/**
 * 编辑App
 */
function copyApp(id, pkgname)
{
	var apps_edit_box = $('#fuelux-wizard');

	apps_edit_box.attr('action','?m=admin&c=apps&a=copy');
	apps_edit_box.find('.id').val('');
	$('#id').val(id);
	$('#_step1').click();
	$.get('?m=admin&c=apps&a=lists&_c=appsData&_a=getAppInfoByid', {id:id},function(data){
		//console.log(data);
		if(data.status != 200)
		{
			notice('Can not match any record by this id: '+ id);
			return false;
		}
		//fill fields
		data = data.content.data;
		for(var item in data)
		{
			try{
				var _type = document.getElementById(item).type;
				switch(_type)
				{
					case 'textarea':
						$('#'+item).html(data[item]);
						break;
					case 'text':
						$('#'+item).val(data[item]);
						break;
					default:
						$('#'+item).val(data[item]);
					break;
						break;
				}
			}catch(e){}
		}
		var _place = $(':radio[name="k[place]"]');
		_place.each(function(a,b){
			if($(this).val() == data['place'])
			{
				$(this).prop('checked',true);
			}
		});
		//脸谱radio
		var _sex = $(':radio[name="k[sex]"]');
		_sex.each(function(a,b){
			if($(this).val() == data['sex'])
			{
				$(this).prop('checked',true);
			}
		});
		var _app_installed_num_limit = $(':radio[name="k[app_installed_num_limit]"]');
		_app_installed_num_limit.each(function(a,b){
			if($(this).val() ==  data['app_installed_num_limit'])
			{
				$(this).prop('checked',true);
			}
		});
		$('#dialog-edit-box-apps-lists').dialog({title:'Copy App:  ' + pkgname});
		$('#dialog-edit-box-apps-lists').dialog('open');
		
		targetedCategoryIDsSellect2();
		subjectidSelect2();
		posidSelect2();
		facebook_tagsSelect2();
	});
}
/**
 * 编辑创意
 */
function editIdea(id, title)
{
	var idea_edit_box = $('#fuelux-wizard-ideas');

	idea_edit_box.attr('action','?m=admin&c=apps&a=editIdea');
	idea_edit_box.find('.id').val(id);

	$('#_ideas_step11').click();
	$.get('?m=admin&c=apps&a=lists&_c=appsData&_a=getIdeaInfoByid', {id:id},function(data){
		//console.log(data);
		if(data.status != 200)
		{
			notice('Can not match any record by this id: '+ id);
			return false;
		}
		//fill fields
		data = data.content.data;
		for(var item in data)
		{
			_item = "ideas_"+item;
			try{
				var _type = document.getElementById(_item).type;
				switch(_type)
				{
					case 'textarea':
						//$('#'+_item).html(data[item]);
						$('#'+_item).val(data[item]);
						break;
					case 'text':
						$('#'+_item).val(data[item]);
						break;
					default:
						$('#'+_item).val(data[item]);
						break;
				}
			}catch(e){}
		}
		idea_edit_box.find('.appid').val(data['appid']);
		//填充样式内容
		$('#title_bold').val(data['style_control']['title_bold']);
		$('#title_color').val(data['style_control']['title_color']);
		$('#desc_bold').val(data['style_control']['desc_bold']);
		$('#desc_color').val(data['style_control']['desc_color']);
		$('#pkg_size_bold').val(data['style_control']['pkg_size_bold']);
		$('#pkg_size_color').val(data['style_control']['pkg_size_color']);
		
		setPreviewStyle(data['style_control']['title_bold']?1:0, data['style_control']['title_color']?data['style_control']['title_color']:0, '#app_title');
		setPreviewStyle(data['style_control']['desc_bold']?1:0, data['style_control']['desc_color']?data['style_control']['desc_color']:0, '#app_desc');
		setPreviewStyle(data['style_control']['pkg_size_bold']?1:0, data['style_control']['pkg_size_color']?data['style_control']['pkg_size_color']:0, '#app_pkg_size');
		//加入包名语言
		$.get('?m=admin&c=apps&a=lists&_c=appsData&_a=getAppInfoByid', {id:data['appid']},function(data){
			//console.log(data);
			if(data.status != 200)
			{
				notice('Can not match any record by this id: '+ appid);
				return false;
			}
			//fill fields
			data = data.content.data;
			idea_edit_box.find('.lan').val(data.lan);
			idea_edit_box.find('.pkgname').val(data.pkgname);
			
		});
		$('#dialog-edit-box-ideas').dialog({title:'Edit Creative:  ' + title});
		$('#dialog-edit-box-ideas').dialog('open');
		
	});
}
/**
 * 复制创意
 */
function copyIdea(id, title)
{
	var idea_edit_box = $('#fuelux-wizard-ideas');

	idea_edit_box.attr('action','?m=admin&c=apps&a=copyIdea');
	idea_edit_box.find('.id').val(id);

	$('#_ideas_step11').click();
	$.get('?m=admin&c=apps&a=lists&_c=appsData&_a=getIdeaInfoByid', {id:id},function(data){
		//console.log(data);
		if(data.status != 200)
		{
			notice('Can not match any record by this id: '+ id);
			return false;
		}
		//fill fields
		data = data.content.data;
		for(var item in data)
		{
			_item = "ideas_"+item;
			try{
				var _type = document.getElementById(_item).type;
				switch(_type)
				{
					case 'textarea':
						$('#'+_item).html(data[item]);
						break;
					case 'text':
						$('#'+_item).val(data[item]);
						break;
					default:
						$('#'+_item).val(data[item]);
						break;
				}
			}catch(e){}
		}
		idea_edit_box.find('.appid').val(data['appid']);
		//填充样式内容
		$('#title_bold').val(data['style_control']['title_bold']);
		$('#title_color').val(data['style_control']['title_color']);
		$('#desc_bold').val(data['style_control']['desc_bold']);
		$('#desc_color').val(data['style_control']['desc_color']);
		$('#pkg_size_bold').val(data['style_control']['pkg_size_bold']);
		$('#pkg_size_color').val(data['style_control']['pkg_size_color']);
		
		setPreviewStyle(data['style_control']['title_bold']?1:0, data['style_control']['title_color']?data['style_control']['title_color']:0, '#app_title');
		setPreviewStyle(data['style_control']['desc_bold']?1:0, data['style_control']['desc_color']?data['style_control']['desc_color']:0, '#app_desc');
		setPreviewStyle(data['style_control']['pkg_size_bold']?1:0, data['style_control']['pkg_size_color']?data['style_control']['pkg_size_color']:0, '#app_pkg_size');
		//加入包名语言
		$.get('?m=admin&c=apps&a=lists&_c=appsData&_a=getAppInfoByid', {id:data['appid']},function(data){
			//console.log(data);
			if(data.status != 200)
			{
				notice('Can not match any record by this id: '+ appid);
				return false;
			}
			//fill fields
			data = data.content.data;
			idea_edit_box.find('.lan').val(data.lan);
			idea_edit_box.find('.pkgname').val(data.pkgname);
			
		});
		$('#dialog-edit-box-ideas').dialog({title:'Copy Creative:  ' + title});
		$('#dialog-edit-box-ideas').dialog('open');
		
	});
}

/**
 * 添加创意
 */
function addIdea(appid, title)
{
	var idea_edit_box = $('#fuelux-wizard-ideas');

	idea_edit_box.attr('action','?m=admin&c=apps&a=addIdea');
	idea_edit_box.find('.appid').val(appid);

	$('#_ideas_step11').click();
	//使用任意一条数据清空数据字段
	$.get('?m=admin&c=apps&a=lists&_c=appsData&_a=getIdeaExcemple',function(data){
		//console.log(data);
		if(data.status != 200)
		{
			notice('Can not match any record by this id');
			return false;
		}
		//fill fields
		data = data.content.data;
		for(var item in data)
		{
			_item = "ideas_"+item;
			try{
				var _type = document.getElementById(_item).type;
				switch(_type)
				{
					case 'textarea':
						$('#'+_item).html('');
						break;
					case 'text':
						$('#'+_item).val('');
						break;
					default:
						$('#'+_item).val('');
						break;
				}
			}catch(e){}
		}
		//增加默认流量占比 100%
		$('#ideas_flowpercent').val(100);
		//清空样式内容
		$('#title_bold').val('');
		$('#title_color').val('');
		$('#desc_bold').val('');
		$('#desc_color').val('');
		$('#pkg_size_bold').val('');
		$('#pkg_size_color').val('');
	});
	//
	$.get('?m=admin&c=apps&a=lists&_c=appsData&_a=getAppInfoByid', {id:appid},function(data){
		//console.log(data);
		if(data.status != 200)
		{
			notice('Can not match any record by this id: '+ appid);
			return false;
		}
		//fill fields
		data = data.content.data;
		idea_edit_box.find('.lan').val(data.lan);
		idea_edit_box.find('.pkgname').val(data.pkgname);
		$('#dialog-edit-box-ideas').dialog({title:'Add Creative For:  ' + title});
		$('#dialog-edit-box-ideas').dialog('open');
		
	});
}
/**
 * 显示创意
 * @param obj
 */
function showIdeas(obj)
{
	var _id = $(obj).attr('data-id');
	var _pkgname = $(obj).attr('data-pkgname');
	$.get('?m=admin&c=apps&a=lists&_c=appsData&_a=getCreatives', {appid:_id},function(data){
		if(data.content.data.length == 0)
		{
			data.content.data = "<tr><td colspan='6' align='center'>Empty Record</td></tr>";
		}
		$('#table_ideas').children('tbody').html(data.content.data);
		$('#dialog-message-dialog_ideas').dialog({title:'Creatives Of ' + _pkgname});
		$('#dialog-message-dialog_ideas').dialog('open');
	});
}
/**
 * 预览App
 */
function viewApp(id, title)
{
	notice('This function does not implement');
}

/**
 * 预览Idea
 */
function viewIdea(id, title)
{
	notice('This function does not implement');
}
/**
 * 上传图片
 */
function ajax_upload(files, obj){
	if(files == null)return;
	$(files).each(function(a,file){
		//提供一个可以取消的能力
		window.xhr = $.ajaxSettings.xhr();
		//事件函数
		var onProgressHandler = function(event){//上传进度
			if(event.loaded) {
			    var howmuch = Math.floor((event.loaded / event.total) * 100);
				   // document.getElementById('pint').setAttribute('style','background:red;height:1px;width:'+howmuch+'%');
	
				//$('#objprogress').show().val(howmuch);
			  }else{
				console.log("Can't determine the size of the file.");
			 }
		};
		var onLoadedHandler = function(msg){//请求完成
			//document.getElementById('num').innerHTML = '100%';
		};
		var onAbortHandler = function(){//取消上传
			notice('Aborted');
		};
		//事件绑定
		xhr.upload.addEventListener('progress', onProgressHandler, false);
		xhr.upload.addEventListener('load', onLoadedHandler, false);
		xhr.upload.addEventListener('abort', onAbortHandler, false);
	
		xhr.onreadystatechange = function(event){//上传成功
			if(event.target.readyState == 4 && event.target.status == 200){
				//$('#objprogress').hide().val(0);
				var text = $.parseJSON(event.target.responseText);
				if(text.content.success == 1){
					$(obj).parent().nextAll('input').eq(0).val(text.content.data.pic_url);
					if($(obj).attr('data-for')=='prefix1')
					{
						//为预览图使用本地图片
						$('#app_icon').attr('src',text.content.data.src);
					}
				}else{
					notice('Upload Failure:'+text.content.msg);
				}
			}
		};
		var prefix = $('#'+$(obj).attr('data-for')).val();
		xhr.open('post',ajaxUploadUrl + "&filename=" + file.name + "&prefix=" + prefix,true);
		xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		//xhr.setRequestHeader("X-File-Name", file.name);
		//xhr.setRequestHeader("X-File-Size", file.size);
		//xhr.setRequestHeader("X-File-Type", file.type);
		xhr.send(file);
	});
}
/**
 * 读取谷歌信息
 */
$('#loadinfo').on('click',function(){
	var THIS = $(this).prev();
	THIS.addClass('ui-autocomplete-loading');

	var idea_edit_box = $('#fuelux-wizard-ideas');
	
	var name = idea_edit_box.find('.pkgname').val();
	var lan = idea_edit_box.find('.lan').val();
	
	if(!name){
		notice('Can not find any package name');
		return false;
	}
	
	$('#ideas_click_url').val('https://play.google.com/store/apps/details?id='+name);
	$.get('?m=admin&c=apps&a=public_autoLoad&name='+name+'&lan='+lan,function(data){
		try{
			data = $.parseJSON(data);
		}catch(e){
			notice("Exception:"+e);
		}
		THIS.removeClass('ui-autocomplete-loading');
		if(data.success==0){
			notice(data.msg);
		}else{
			$('#ideas_pic_url').val(data.pic);
			$('#ideas_downloadnum').val(data.dl);
			$('#ideas_rating').val(data.rating);
			$('#ideas_pkg_size').val(data.size);
			$('#ideas_title').val(data.title);
			$('#ideas_likes').val(data.likes);
		}
	});
});
/**
 * 读取GP分类
 */
$('#loadcategory').on('click',function(){
	var THIS = $(this).prev();
	THIS.addClass('ui-autocomplete-loading');

	var app_edit_box = $('#fuelux-wizard');
	
	var name = app_edit_box.find('#pkgname').val();
	var lan  = app_edit_box.find('#lan').val();
	
	if(!name){
		notice('Can not find any package name');
		return false;
	}
	
	$.get('?m=admin&c=apps&a=public_autoLoad&name='+name+'&lan='+lan,function(data){
		try{
			data = $.parseJSON(data);
		}catch(e){
			notice("Exception:"+e);
		}
		THIS.removeClass('ui-autocomplete-loading');
		if(data.success==0){
			notice(data.msg);
		}else{
			THIS.val(data.cat);
		}
	});
});
/**
 * 获取编辑信息
 */
$('#ideas_editor_name').on('click',function(){
	var THIS = $(this);
	THIS.addClass('ui-autocomplete-loading');
	$.get('?m=admin&c=apps&a=public_Editors',function(data){
		//#logincheck(data);
		if(!data)
		{
			notice("Nothing Return");
		}
		THIS.removeClass('ui-autocomplete-loading');
		if(data.content.success==0){
			notice(data.msg);
		}else{
			var CDN_IMG_URL = data.content.CDN_IMG_URL;
			data = data.content.data;
			var html = '<div class="superbox col-sm-12">';
			for(var item in data)
			{
				if(data[item]['pic'].indexOf('http:') !==0)
				{
					data[item]['pic'] = CDN_IMG_URL+data[item]['pic'];
				}
				html += "<div class='superbox-list' onclick='selectEditor(this);' data2='"+data[item]['name']+"' data3='"+data[item]['id']+"'>" +
						'<img class="superbox-img" title="'+data[item]['name']+'" alt="'+data[item]['name']+'" data-img="'+data[item]['pic']+'" src="'+data[item]['pic']+'">' +
						'<center>'+data[item]['name']+'</center>' +
						"</div>";
			}
			html += '</div>';
			notice(html, 'Editor Selector', $(window).width() * 0.5, $(window).height() * 0.5);
		}
	});
});
/**
 * 选择编辑
 */
function selectEditor(obj)
{
	var name = $(obj).attr('data2');
	var id = $(obj).attr('data3');
	$('#ideas_editor_name').val(name);
	$('#ideas_editor').val(id);
	$("#dialog_common").html('');
	$("#dialog-message-common").dialog('close');
}
/**
 * Notice Dialog
 */
function notice(msg, title, width, height)
{
	var title = arguments[1] ? arguments[1] : '';
	var width = arguments[2] ? arguments[2] : '';
	var height = arguments[3] ? arguments[3] : '';
	
	var conf = {};
	if(!msg)return false;
	if(title)
	{
		conf.title = title;
	}
	if(width)
	{
		conf.width = width;
	}
	if(height)
	{
		conf.height = height;
	}
	$('#dialog-message-common').dialog(conf);
	$("#dialog_common").html(msg);
	$("#dialog-message-common").dialog('open');
}
/**
*样式控制
*/
function styleControl(obj, t)
{
	var colormap = {"#adadad":1, "#666":10, "#333":11, "#3463b4":100, "#ff7c7c":101};
	var color = $(obj).attr('data-c');
	var _element = document.getElementById('ideas_' + t);
	if(_element.type == 'textarea')
	{
		var text = $('#ideas_' + t).html();
	}else{
		var text = $('#ideas_' + t).val();
	}
	switch(color)
	{
		case 'clear':
			$('#'+ t + '_bold').val(0);
			$('#'+ t + '_color').val('');
			$("#app_"+ t).removeClass('font-bold').removeAttr('style');
			break;
		case 'bold':
			$('#'+ t + '_bold').val(1);
			$("#app_"+ t).addClass('font-bold');
			break;
		default:
			$('#'+ t + '_color').val(colormap[color]);
			$("#app_"+ t).attr('style','color:'+color);
			break;
	}
	
}
//设置预览状态,通过系统的值来判定。
function setPreviewStyle(bold, color, target){
	if(bold == 1){
		$(target).addClass("font-bold");
	}else{
		$(target).removeClass("font-bold");
	}
	var previewColor="";
	color = parseInt(color);
	switch(color){
		case 1:
			previewColor ="#adadad";
			break;
		case 10:
			previewColor = "#666";
			break;
		case 11:
			previewColor  = "#333";
			break;
		case 100:
			previewColor = "#3463b4";
			break;
		case 101:
			previewColor = "#ff7c7c";
			break;
	}
	if(previewColor){
		$(target).attr("style","color:"+previewColor);
	}else{
		$(target).removeAttr("style");
	}
}
/**
 * 事件监控字体样式更改
 */

$(function(){
	$("#ideas_title").bind("change paste keyup", function(){
			var title = $(this).val();
			if(!title){
				title = "App Title";
				}
			$("#app_title").text(title);
		});
	$("#ideas_desc").bind("change paste keyup", function(){
		var desc = $(this).val();
		if(!desc){
			desc = "App Description"
		}
		$("#app_desc").text(desc);
	});
	$("#ideas_button_txt").bind("change paste keyup", function(){
		var button = $(this).val();
		if(!button){
			button = "download";
			}
		$("#app_button").text(button);
	});
	$("#ideas_pkg_size").bind("change paste keyup", function(){
		var text = $(this).val();
		if(!text){
			text = "";
			}
		$("#app_pkg_size").text(text);
	});
	$("#ideas_pic_url").bind("change paste keyup", function(){
		var text = $(this).val();
		if(!text){
			text = "";
			}
		$("#app_icon").attr("src", text);
	});
})

$('#currentTime').click(function(){
	var myDate = new Date();
	var y = myDate.getFullYear();    //获取完整的年份(4位,1970-????)
	var m = myDate.getMonth()+1;       //获取当前月份(0-11,0代表1月)
	var d = myDate.getDate();        //获取当前日(1-31)
	var h = myDate.getHours();       //获取当前小时数(0-23)
	var min = myDate.getMinutes();     //获取当前分钟数(0-59)
	var s = myDate.getSeconds();     //获取当前秒数(0-59)
	m = m<10?'0'+m:m;
	d = d<10?'0'+d:d;
	h = h<10?'0'+h:h;
	min = min<10?'0'+min:min;
	s = s<10?'0'+s:s;
	$('#timestamp').val(y+'-'+m+'-'+d+' '+h+':'+min+':'+s);//获取日期与时间  
});
/**
 * POSID
 */
//$('#posid').on("change", function(e) { console.log("change "+JSON.stringify({val:e.val, added:e.added, removed:e.removed})); });
function posidSelect2()
{
	$('#posid').select2({
		id: function(e) { return e.posid; },
	    placeholder          : "Search for a repository",
	    minimumInputLength   : 1,
	    multiple             : true,
	    separator            : "|",                             // 分隔符
	    maximumSelectionSize : 30,                               // 限制数量
	    initSelection        : function (element, callback) {   // 初始化时设置默认值
	        var data = [];
	        $(element.val().split("|")).each(function () {
	            data.push({posid: this, name: this});
	        });
	        callback(data);
	    },
	    createSearchChoice   : function(term, data) {           // 创建搜索结果（使用户可以输入匹配值以外的其它值）
	        //return { posid: term, name: term };
	    },
	    formatSelection : function (item) { return item.posid; },  // 选择结果中的显示
	
		formatResult: function(repo)
		{
			var markup = "<div><span class='padding-10'>" + repo.posid + "</span><span class='padding-10'>" + repo.name + "</span></div>";
			return markup;
		},  // 搜索列表中的显示
	    ajax : {
	        url      : "?m=admin&c=apps&a=lists&_c=appsData&_a=getPosid",              // 异步请求地址
	        dataType : "json",                  // 数据类型
	        data     : function (term, page) {  // 请求参数（GET）
	            return { query: term };
	        },
	        results      : function (data, page) { return data.content; },  // 构造返回结果
	        escapeMarkup : function (m) { return m; }               // 字符转义处理
	    }
	});
}
/**
 * SUBJECTID
 */
//$('#posid').on("change", function(e) { console.log("change "+JSON.stringify({val:e.val, added:e.added, removed:e.removed})); });
function subjectidSelect2()
{
	$('#subjectid').select2({
		id: function(e) { return e.posid; },
	    placeholder          : "Search for a repository",
	    minimumInputLength   : 1,
	    multiple             : true,
	    separator            : ",",                             // 分隔符
	    maximumSelectionSize : 30,                               // 限制数量
	    initSelection        : function (element, callback) {   // 初始化时设置默认值
	        var data = [];
	        $(element.val().split(",")).each(function () {
	            data.push({posid: this, name: this});
	        });
	        callback(data);
	    },
	    createSearchChoice   : function(term, data) {           // 创建搜索结果（使用户可以输入匹配值以外的其它值）
	        //return { posid: term, name: term };
	    },
	    formatSelection : function (item) { return item.posid; },  // 选择结果中的显示
	
		formatResult: function(repo)
		{
			var markup = "<div><span class='padding-10'>" + repo.posid + "</span><span class='padding-10'>" + repo.name + "</span></div>";
			return markup;
		},  // 搜索列表中的显示
	    ajax : {
	        url      : "?m=admin&c=apps&a=lists&_c=appsData&_a=getPosid",              // 异步请求地址
	        dataType : "json",                  // 数据类型
	        data     : function (term, page) {  // 请求参数（GET）
	            return { query: term };
	        },
	        results      : function (data, page) { return data.content; },  // 构造返回结果
	        escapeMarkup : function (m) { return m; }               // 字符转义处理
	    }
	});
}
/**
 * 分类触发
 */
//$('#posid').on("change", function(e) { console.log("change "+JSON.stringify({val:e.val, added:e.added, removed:e.removed})); });
function targetedCategoryIDsSellect2()
{
	$('#targetedCategoryIDs').select2({
		id: function(e) { return e.id; },
	    placeholder          : "Search for a repository",
	    minimumInputLength   : 1,
	    multiple             : true,
	    separator            : ",",                             // 分隔符
	    maximumSelectionSize : 30,                               // 限制数量
	    initSelection        : function (element, callback) {   // 初始化时设置默认值
	        var data = [];
	        $(element.val().split(",")).each(function () {
	            data.push({id: this, name: this, enname:this});
	        });
	        callback(data);
	    },
	    createSearchChoice   : function(term, data) {           // 创建搜索结果（使用户可以输入匹配值以外的其它值）
	        //return { id: term, name: term , enname:term};
	    },
	    formatSelection : function (item) { return item.id; },  // 选择结果中的显示
	
		formatResult: function(repo)
		{
			var markup = "<div><span class='padding-10'>" + repo.id + "</span><span class='padding-10'>" + repo.name + "</span><span class='padding-10'>(" + repo.enname + ")</span></div>";
			return markup;
		},  // 搜索列表中的显示
	    ajax : {
	        url      : "?m=admin&c=apps&a=lists&_c=appsData&_a=getGPCat",              // 异步请求地址
	        dataType : "json",                  // 数据类型
	        data     : function (term, page) {  // 请求参数（GET）
	            return { query: term };
	        },
	        results      : function (data, page) { return data.content; },  // 构造返回结果
	        escapeMarkup : function (m) { return m; }               // 字符转义处理
	    }
	});
}
//创意状态编辑
function idea_handle(obj)
{
	var THIS 	= $(obj);
	var id	= THIS.attr('data-id');
	var appid	= THIS.attr('data-appid');
	var state	= THIS.attr('data-state');
	$.get('?m=admin&c=apps&a=ideahandle',{ id:id, appid:appid, state:state},function(data){
		if(data.status != 200)
		{
			notice('Can not connect to the server');
			return false;
		}
		if(data.content.success == 1)
		{
			THIS.attr('data-state',data.content.data.state);
			var _i = THIS.children('i');
			if(data.content.data.state == 1)
			{
				_i.removeAttr('class');
				_i.addClass('fa txt-color-green fa-check');
			}else{
				_i.removeAttr('class');
				_i.addClass('fa txt-color-red fa-times');
			}
			//创意更改会改变app属性,刷新table列表
	   	    window.datatable.fnDraw();
		}else{
			notice(data.content.msg);
			return false;
		}
	});
}


